package com.hr.config;

import com.hr.model.Menu;
import com.hr.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 分析所需的权限
 */
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource
{
    @Autowired
    MenuService menuService;
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException
    {
        FilterInvocation filterInvocation=(FilterInvocation) object;
        HttpServletRequest request= filterInvocation.getRequest();
        String requestUrl = filterInvocation.getRequestUrl();
        List<Menu> menus = menuService.getAllMenus();
        for (Menu menu : menus) {
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                if(menu.getRequire()==null)
                    continue;
                List<String> requires = new ArrayList<>();
                requires.add(menu.getRequire());
                String[] str = new String[requires.size()];
                for (int i = 0; i < requires.size(); i++) {
                    str[i] = request.getParameter("cid")+"_"+requires.get(i); //权限格式为 {公司id}+"_"+{权限等级}
                }
                return SecurityConfig.createList(str);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
